'use strict';
const mongoose = require('mongoose');
const md5 = require('md5');

let schema = new mongoose.Schema({
    loginId:{
        type:String,
        default:''
    },
    loginPass:{
        type:String,
        default:''
    },
    name: String,
    sort:{
        type:Number,
        default:0
    },
    startCount:{ //默认开始扣量总数
        type:Number,
        default:1000
    },
    percent:{ //默认扣量比例
        type: Number,
        default: 100
    },
    allCount:{  //总计量
        type:Number,
        default:0
    },
    census:{ //统计管理
        type:require('./channel.census'),
        default:{}
    },
    status: {
        type: Number,
        "default": 0   //0代表普通管理员  10代表超级管理员  -1代表该管理员被禁止登陆
    }
});
schema.index({loginId: 1});

schema.statics = {
    list:async function(){

    },
    //验证登陆，如果成功登陆，则返回token
    checkLogin: async function (loginId, password) {
        let channel = await this.findOne({loginId: loginId});
        if (!!channel && channel.loginPass === password) {
            // let token = md5(new Date().getTime().toString());
            // await this.update({loginId: loginId}, {$set: {token: token}}).exec();
            // return {loginId: loginId, token: token};
            return channel;
        } else {
            return false;
        }
    },
    //验证用户token是否合法
    checkToken: async function (loginId, token) {
        let admin = await this.findOne({loginId: loginId, token: token});
        return admin;
    }
};

schema.methods = {
    //验证修改密码，如果成功修改，则返回token
    changePwd: async function (options) {
        if (this.loginPass === options.oldPwd) {
            this.loginPass = options.newPwd;
            // // this.token = md5(new Date().getTime().toString());
            // await this.save();
            // return {loginId: this.loginId, token: this.token};
            return true;
        } else {
            return false;
        }
    },
};

module.exports = schema;